package com.codetile.batch.config;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.builder.JobStepBuilder;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 嵌套Job
 */
@Configuration
@EnableBatchProcessing
public class NestedDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private Job subJob11;

    @Autowired
    private Job subJob21;

    @Autowired
    private JobLauncher jobLauncher;


    @Bean
    public Step subJobStep1(JobRepository repository, PlatformTransactionManager transactionManager){
        return new JobStepBuilder(new StepBuilder("subJob11"))
                .job(subJob11)
                .launcher(jobLauncher)
                .repository(repository)
                .transactionManager(transactionManager)
                .build();
    }

    @Bean
    public Step subJobStep2(JobRepository repository, PlatformTransactionManager transactionManager){
        return new JobStepBuilder(new StepBuilder("subJob21"))
                .job(subJob21)
                .launcher(jobLauncher)
                .repository(repository)
                .transactionManager(transactionManager)
                .build();
    }

    @Bean
    public Job nestedJob(JobRepository repository, PlatformTransactionManager transactionManager){
        return jobBuilderFactory.get("nestedJob")
                .start(subJobStep1(repository,transactionManager))
                .next(subJobStep2(repository,transactionManager))
                .build();
    }

}
